package za.co.dylanjaneke.airdownloader.command
{
	import com.adobe.serialization.json.JSON;
	
	import mx.controls.Alert;
	import mx.rpc.AsyncToken;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.http.HTTPService;
	
	import za.co.dylanjaneke.airdownloader.events.ShowDayEvent;
	import za.co.dylanjaneke.airdownloader.model.DayViewPM;
	import za.co.dylanjaneke.airdownloader.model.HomeScreenPM;
	import za.co.dylanjaneke.airdownloader.model.ScreenNavigatorPM;
	import za.co.dylanjaneke.airdownloader.model.SettingsScreenPM;
	import za.co.dylanjaneke.airdownloader.model.StatusPM;
	import za.co.dylanjaneke.airdownloader.model.TrackerSettingsScreenPM;
	import za.co.dylanjaneke.airdownloader.model.vo.DownloadSiteVO;
	import za.co.dylanjaneke.airdownloader.model.vo.ShowVO;
	import za.co.dylanjaneke.airdownloader.util.ViLogger;

	/**
	 * Author: Dylan Janeke.
	 */
	[Name("showDayCommand")]
	public class ShowDayCommand
	{
		private static const log:ViLogger=
			new ViLogger(ShowDayCommand);
		
		[Inject]
		public var screenNavigatorPM:ScreenNavigatorPM;
		
		[Inject]
		public var homeScreenPM:HomeScreenPM;
		
		[Inject]
		public var dayViewPM:DayViewPM;
		
		[Inject]
		public var statusPM:StatusPM;
		
		[Inject]
		public var settings:TrackerSettingsScreenPM;
		
		private var complete:Number=0;
		
		[Observer]
		public function handleShowDayEvent(event:ShowDayEvent): void
		{
			dayViewPM.day= event.day;
			statusPM.status= "loading shows for "+ event.day.date;
			
			if(dayViewPM.day.shows.length==0)
			{
				Alert.show("No shows are tracked for this day.", "No shows found.");
			}
			fetchLinks();
		}
		
		protected function fetchLinks(): void
		{
			complete=0;
			
			statusPM.status = "getting download links...";
			
			for each(var show:ShowVO in dayViewPM.day.shows)
			{
				var gService:HTTPService= new HTTPService();
				gService.url = "http://ajax.googleapis.com/ajax/services/search/web";
				gService.request.v = "1.0";
				gService.request.key = "ABQIAAAAN-E9tu9RMW53zHy72qakFRSBN9CU20Vt0aWQg__l5_XT0n8tuhTk7_7J2YUchXAl38LZaw6nR3Z3xA";
				var query:String= show.showName+" s"+show.seasonNumber+"e"+show.episodeNumber+" ";
				
				var i:int=0;
				for each(var downloadSite:DownloadSiteVO in settings.sites)
				{
					query += (i==0?" ": " || ") + "site:"+downloadSite.url;
					i++;
				}
			
				log.info("query-->"+query);
				
				gService.request.q= query;
				gService.method="GET";
				gService.resultFormat = 'text';
				gService.addEventListener(ResultEvent.RESULT, onGoogleResult);
				
				show.asyncToken= gService.send();
			}
		}
		
		protected function onGoogleResult(event:ResultEvent): void
		{
			complete++;
			var responseToken:AsyncToken= event.token;
			
			for each (var show:ShowVO in dayViewPM.day.shows)
			{
				if(show.asyncToken!=responseToken)
				{
					continue;
				}
				try
				{
					var response:Object= JSON.decode(event.result as String);
					var results:Array= response.responseData.results;
					for each(var result:Object in results)
					{
						if(result.url.indexOf("hotfile.com/list/") > -1)
						{
							continue;							
						}
						
						var linkvo:ShowVO= new ShowVO();
						linkvo.url= result.url;
						
						var ctent:String= result.content;
						
						linkvo.urlTitle= result.url+"\n\n"+ ctent;
						
						var hasLink:Boolean= false;
						for each(var link:ShowVO in show.children)
						{
							if(link.url == linkvo.url)
							{
								hasLink= true;								
							}
						}
						if(!hasLink)
							show.children.addItem(linkvo);
					}
				}
				catch(ignored:Error){}
			}
			
			if(dayViewPM.day.shows.length==complete)
			{
				statusPM.status = "http://code.google.com/p/vicariousdownloader/";
				homeScreenPM.switchView(HomeScreenPM.DAY);	
			}
		}
	}
}